//
//  CloudPrint.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/9.
//

#import "CloudPrint.h"
#import "AFNetworking.h"
#import "SASalesInvoiceDetailAPI.h"
#import "SAWarehousePurchaseInvoiceDetailAPI.h"
#import "SAPrintReturn.h"
#import "SASalesReturnDetailAPI.h"
#import "SAPrintLableModel.h"
#import "ConnecterManager.h"
#import "EscCommand.h"
#import "TscCommand.h"
#import "SACommoditySpecialFeesModel.h"
#import "ZXMultiFormatWriter.h"
#import "ZXImage.h"
//#import "PrintfTSPLManager.h"
//#import "BluetoothManager2.h"

@interface CloudPrint ()<HTTPAPIDelegate>

@property (nonatomic, strong) SASalesInvoiceDetailAPI *salesInvoiceDetailAPI;
@property (nonatomic, strong) SAWarehousePurchaseInvoiceDetailAPI *warehousePurchaseInvoiceDetailAPI;
@property (nonatomic, strong) SASalesReturnDetailAPI *salesReturnDetailAPI;

@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) NSString *printName;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger seconds;
@property (nonatomic, strong) NSMutableArray *codeMarr;

//@property (nonatomic, assign) NSInteger saleSeconds;
@property (nonatomic, strong) NSMutableArray *saleMarr;

//@property (nonatomic, assign) NSInteger returnSeconds;
@property (nonatomic, strong) NSMutableArray *returnMarr;

//@property (nonatomic, assign) NSInteger WarehousingSeconds;
@property (nonatomic, strong) NSMutableArray *WarehousingMarr;

@end

@implementation CloudPrint

static CloudPrint *cloudPrint;
+ (CloudPrint *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cloudPrint = [[CloudPrint alloc] init];
        [cloudPrint initData];
    });
    return cloudPrint;
}

-(void)initData {
    self.overallSetting = [SAOverallSetting shareInstance];
    self.seconds = 0;
    self.codeMarr = [NSMutableArray array];
    //    self.saleSeconds = 0;
    self.saleMarr = [NSMutableArray array];
    //    self.returnSeconds = 0;
    self.returnMarr = [NSMutableArray array];
    //    self.WarehousingSeconds = 0;
    self.WarehousingMarr = [NSMutableArray array];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

-(void)timerFired {
    if (self.seconds == 1) {
        NSMutableArray<SAPrintLableModel *> *marr = [NSMutableArray array];
        for (NSString *data in self.codeMarr) {
            NSMutableArray<SAPrintLableModel *> *list = [SAPrintLableModel mj_objectArrayWithKeyValuesArray:data];
            for (SAPrintLableModel *model in list) {
                if (model.barcodeSingle.length > 0) {
                    model.barcode = model.barcodeSingle;
                }
                [marr addObject:model];
            }
        }
        if ([SAValueManger shareInStance].printType == 2) {
            if (marr.count > 0) {
                [self printBarcode:marr];
            }
            if (self.codeMarr.count > 0) {
                self.seconds = 4;
                [self.codeMarr removeAllObjects];
                [self.saleMarr removeAllObjects];
                [self.WarehousingMarr removeAllObjects];
                return;
            }else {
                self.seconds = 0;
            }
        }else if ([SAValueManger shareInStance].printType == 1) {
            [self.codeMarr removeAllObjects];
            self.seconds = 0;
            if (self.saleMarr.count > 0) {
                self.seconds = 4;
                NSString *data = self.saleMarr[0];
                [self printSale2:data];
                [self.saleMarr removeObject:data];
                return;
            }
            
            if (self.returnMarr.count > 0) {
                self.seconds = 4;
                NSString *data = self.returnMarr[0];
                [self printReturn2:data];
                [self.returnMarr removeObject:data];
                
                return;
            }
            
            if (self.WarehousingMarr.count > 0) {
                self.seconds = 4;
                NSString *data = self.WarehousingMarr[0];
                [self printWarehousing2:data];
                [self.WarehousingMarr removeObject:data];
                return;
            }
        }
    }else if (self.seconds > 1){
        self.seconds--;
    }else {
        self.seconds = 0;
    }
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

-(void)PrintWithType:(NSString *)type AndData:(NSString *)data {
    //1小票打印 2小票退货打印 3小票入库打印 4商品条码打印 5单品条码打印
    if ([type isEqualToString:@"1"]) {
        [self printSale:data];//小票打印
    }else if ([type isEqualToString:@"2"]) {
        [self printReturn:data];//小票退货打印
    }else if ([type isEqualToString:@"3"]) {
        [self printWarehousing:data];//入库打印
    }else if ([type isEqualToString:@"4"]) {
        [self printProductCode:data];
    }else if ([type isEqualToString:@"5"]) {
        [self printProductCode:data];
    }
}

//销售小票打印
-(void)printSale:(NSString *)data {
    NSInteger printType = [SAValueManger shareInStance].printType;
    if (printType == 1) {
        if (self.seconds == 0) {
            self.seconds = 4;
            [self printSale2:data];
        }else {
            [self.saleMarr addObject:data];
        }
    }
}

-(void)printSale2:(NSString *)data {
    self.salesInvoiceDetailAPI.salesOrderId = data;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置请求类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    [manager GET:self.salesInvoiceDetailAPI.url parameters:self.salesInvoiceDetailAPI.parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SASalesInvoiceDetailModel *salesInvoiceDetailModel = [SASalesInvoiceDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
        [SAPrintReceiptSell printWithTotalData:salesInvoiceDetailModel printSuccessBlock:^{
            
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

-(void)printReturn:(NSString *)data {
    NSInteger printType = [SAValueManger shareInStance].printType;
    if (printType == 1) {
        if (self.seconds == 0) {
            self.seconds = 4;
            [self printReturn2:data];
        }else {
            [self.returnMarr addObject:data];
        }
    }
}

-(void)printReturn2:(NSString *)data {
    self.salesReturnDetailAPI.salesReturnOrderId = data;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置请求类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    [manager GET:self.salesInvoiceDetailAPI.url parameters:self.salesInvoiceDetailAPI.parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SASalesInvoiceDetailModel *salesInvoiceDetailModel = [SASalesInvoiceDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
        [SAPrintReturn printWithTotalData:salesInvoiceDetailModel printSuccessBlock:^{
            
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//入库小票打印
-(void)printWarehousing:(NSString *)data {
    if ([SAValueManger shareInStance].printType == 1) {
        if (self.seconds == 0) {
            self.seconds = 4;
            [self printWarehousing2:data];
        }else {
            [self.WarehousingMarr addObject:data];
        }
    }
}

-(void)printWarehousing2:(NSString *)data {
    self.warehousePurchaseInvoiceDetailAPI.purchaseOrderId = data;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置请求类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    [manager GET:self.warehousePurchaseInvoiceDetailAPI.url parameters:self.warehousePurchaseInvoiceDetailAPI.parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SACommodityWarehousingSingleModel *salesInvoiceDetailModel = [SACommodityWarehousingSingleModel mj_objectWithKeyValues:responseObject[@"data"]];
        [SAPrintReceiptStorage printWithTotalData:salesInvoiceDetailModel printSuccessBlock:^{
            
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//标签打印
-(void)printProductCode:(NSString *)data {
    NSInteger printType = [SAValueManger shareInStance].printType;
    NSMutableArray<SAPrintLableModel *> *marr = [SAPrintLableModel mj_objectArrayWithKeyValuesArray:data];
    for (SAPrintLableModel *model in marr) {
        if (model.barcodeSingle.length > 0) {
            model.barcode = model.barcodeSingle;
        }
    }
    if (printType == 2) {
        if (self.seconds == 0) {
            self.seconds = 4;
            [self printBarcode:marr];
        }else {
            [self.codeMarr addObject:data];
        }
    }
}

-(void)printBarcode:(NSMutableArray<SAPrintLableModel *> *)marr {
    //    BluetoothManager2 *blueToothManager = [BluetoothManager2 bluetoothManagerInstance];
    
    for (SAPrintLableModel *model in marr) {
        NSData *data = [self connectionData:model];
        if (data != nil) {
            [Manager write:data progress:^(NSUInteger total, NSUInteger progress) {
            } receCallBack:^(NSData * _Nullable data) {
            }];
        }
    }
}

//拼接打印条码的数据
-(NSData *)connectionData:(SAPrintLableModel *)model {
    int printNum = [model.printNum intValue];
    if (printNum == 0) {
        return nil;
    }
    
    NSString *printName = kPrint;
    //对成分特殊处理
    model.component1 = @"";
    model.component2 = @"";
    model.productName1 = @"";
    model.productName2 = @"";
    model.ground1 = @"";
    model.ground2 = @"";
    SACommoditySpecialFeesModel *labelLayout = self.overallSetting.labelLayout;
    SACommoditySpecialFeesModel *labelLayoutAttribute = self.overallSetting.labelLayoutAttribute;
    SACommoditySpecialFeesModel *sizeValue = self.overallSetting.sizeValue4030;
    NSString *storeName = [SAValueManger shareInStance].userInfo.storeName;
    if (storeName.length == 0) {
        storeName = @"";
    }
    BOOL isHongKong = NO;
    SACommoditySpecialFeesModel *hkSymbol = [SAOverallSetting shareInstance].hkSymbol;
    if ([hkSymbol.value isEqualToString:@"1"]) {
        isHongKong = YES;
    }
    
    int width = 320;
    UIView *bitView = [[UIView alloc] init];
    bitView.backgroundColor = [UIColor whiteColor];
    TscCommand *command = [[TscCommand alloc] init];
    if ([labelLayout.value isEqualToString:@"1"]) {
        [command addSize:40 :60];
        labelLayoutAttribute = self.overallSetting.labelLayoutAttribute4060;
        sizeValue = self.overallSetting.sizeValue4060;
        bitView.frame = CGRectMake(0, 0, 320, 480);
    }else if ([labelLayout.value isEqualToString:@"2"]){
        [command addSize:40 :80];
        labelLayoutAttribute = self.overallSetting.labelLayoutAttribute4080;
        sizeValue = self.overallSetting.sizeValue4080;
        bitView.frame = CGRectMake(0, 0, 320, 640);
    }else if ([labelLayout.value isEqualToString:@"3"]){
        width = 240;
        [command addSize:30 :20];
        labelLayoutAttribute = self.overallSetting.labelLayoutAttribute3020;
        sizeValue = self.overallSetting.sizeValue3020;
        bitView.frame = CGRectMake(0, 0, 240, 160);
    }else if ([labelLayout.value isEqualToString:@"4"]) {
        width = 480;
        [command addSize:60 :40];
        labelLayoutAttribute = self.overallSetting.labelLayoutAttribute6040;
        sizeValue = self.overallSetting.sizeValue6040;
        bitView.frame = CGRectMake(0, 0, 480, 320);
    }else{
        [command addSize:40 :30];
        labelLayoutAttribute = self.overallSetting.labelLayoutAttribute4030;
        sizeValue = self.overallSetting.sizeValue4030;
        bitView.frame = CGRectMake(0, 0, 320, 240);
    }
    
    NSString *printDirection = kPrintDirection;
    if (printDirection != nil && [printDirection isEqualToString:@"1"]) {
        printDirection = @"1";
    } else {
        printDirection = @"0";
    }
    [command addDirection:printDirection.intValue];
    [command addCls];
    
    [command addGapWithM:2 withN:0];
    [command addReference:0 :0];
    [command addTear:@"ON"];
    [command addQueryPrinterStatus:ON];
    
    NSArray *arr = [labelLayoutAttribute.value componentsSeparatedByString:@","];
    //    arr = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"-7",@"-8",@"-9",@"-10",@"-11",@"12"];
    
    BOOL haveBigFont = NO;
    for (int i = 0; i < arr.count; i++) {
        NSString *arrStr =  [NSString stringWithFormat:@"+%@",arr[i]];
        if ([sizeValue.value containsString:arrStr]) {
            haveBigFont = YES;
        }
    }
    if ([printName isEqualToString:@"YDT-BQ1"]) {
        haveBigFont = YES;
    }
    
    int x = 0;
    int y = 0;
    int j = 30; //间距
    int top = 0;
    NSString *printLeft = kPrintLeft;
    NSString *printTop = kPrintTop;
    if (printLeft != nil && printLeft.length > 0) {
        x = printLeft.intValue;
    }
    
    if (printTop != nil && printTop.length > 0) {
        y = printTop.intValue;
        top = printTop.intValue;
    }
    
    if (haveBigFont) {
        int font = 24;
        int bigFont = 36;
        int labSpace = 8;//字体间距
        BOOL isBarcode = false;
        if ([labelLayout.value isEqualToString:@"0"] || [labelLayout.value isEqualToString:@"3"]) {
            labSpace = 4;//字体间距
        }
        
        if ([labelLayout.value isEqualToString:@"1"] || [labelLayout.value isEqualToString:@"2"]) {
            int count = 0;
            for (int i = 0; i < arr.count; i++) {
                NSString *arrStr = arr[i];
                if (i == 0) {
                    if ([arrStr isEqualToString:@"0"]) {
                        count++;
                    }
                }else if ([arrStr isEqualToString:@"7"]) {
                    //                model.component
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.component length];i++){
                        int a = [model.component characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 108 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 108 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.component1 = [model.component substringToIndex:len - 3];
                            model.component2 = [model.component substringFromIndex:len - 3];
                        }else {
                            model.component1 = [model.component substringToIndex:len];
                            model.component2 = [model.component substringFromIndex:len];
                        }
                    }
                    count++;
                    
                }else if ([arrStr isEqualToString:@"2"]) {
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.productName length];i++){
                        int a = [model.productName characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 108 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 108 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.productName1 = [model.productName substringToIndex:len - 3];
                            model.productName2 = [model.productName substringFromIndex:len - 3];
                        }else {
                            model.productName1 = [model.productName substringToIndex:len];
                            model.productName2 = [model.productName substringFromIndex:len];
                        }
                    }
                    count++;
                }else if ([arrStr isEqualToString:@"16"]) {
                    //                model.ground
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.ground length];i++){
                        int a = [model.ground characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 108 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 108 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.ground1 = [model.ground substringToIndex:len - 3];
                            model.ground2 = [model.ground substringFromIndex:len - 3];
                        }else {
                            model.ground1 = [model.ground substringToIndex:len];
                            model.ground2 = [model.ground substringFromIndex:len];
                        }
                    }
                    count++;
                }else {
                    if ([arrStr integerValue] > 0) {
                        count++;
                    }
                }
            }
        }
        
        //适配美恒通
        int MHT_x = 0;
        int MHT_y = 0;
        if ([printName isEqualToString:@"MHT-L58G"]  || [printName isEqualToString:@"XP-T202UA"]) {
            [command addDensity:10];
            MHT_x = 24;
            MHT_y = 8;
        }
        for (int i = 0; i < arr.count; i++) {
            NSString *arrStr = arr[i];
            if ([arrStr isEqualToString:@"0"]) {
                int height = font;
                if ([sizeValue.value containsString:@"+0"]) {
                    height = bigFont;
                }
                UILabel *storeNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                storeNameLab.text = storeName;
                storeNameLab.textAlignment = NSTextAlignmentCenter;
                storeNameLab.textColor = kBlackColor;
                storeNameLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:storeNameLab];
                y += height + labSpace;
            }
            
            if ([arrStr isEqualToString:@"1"]) {
                NSString *productCode = [NSString stringWithFormat:@"款号: %@",model.productCode];
                int height = font;
                if ([sizeValue.value containsString:@"+1"]) {
                    height = bigFont;
                }
                UILabel *productCodeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                productCodeLab.text = productCode;
                productCodeLab.textAlignment = NSTextAlignmentLeft;
                productCodeLab.textColor = kBlackColor;
                productCodeLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:productCodeLab];
                y += height + labSpace;
                
            }
            if ([arrStr isEqualToString:@"2"]) {
                NSString *productName = [NSString stringWithFormat:@"名称: %@",model.productName];
                int height = font;
                if ([sizeValue.value containsString:@"+2"]) {
                    height = bigFont;
                }
                if (model.productName2.length > 0) {
                    height = height * 2;
                }
                UILabel *productNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width - x - 20, height + labSpace)];
                productNameLab.text = productName;
                productNameLab.textAlignment = NSTextAlignmentLeft;
                productNameLab.textColor = kBlackColor;
                productNameLab.font = [UIFont systemFontOfSize:height];
                if (model.productName2.length > 0) {
                    productNameLab.font = [UIFont systemFontOfSize:height/2];
                }
                productNameLab.numberOfLines = 2;
                [bitView addSubview:productNameLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"3"] && model.color.length > 0) {
                NSString *color = [NSString stringWithFormat:@"颜色: %@",model.color];
                int height = font;
                if ([sizeValue.value containsString:@"+3"]) {
                    height = bigFont;
                }
                UILabel *colorLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                colorLab.text = color;
                colorLab.textAlignment = NSTextAlignmentLeft;
                colorLab.textColor = kBlackColor;
                colorLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:colorLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"4"] && model.size.length > 0) {
                NSString *size = [NSString stringWithFormat:@"尺码: %@",model.size];
                int height = font;
                if ([sizeValue.value containsString:@"+4"]) {
                    height = bigFont;
                }
                UILabel *sizeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                sizeLab.text = size;
                sizeLab.textAlignment = NSTextAlignmentLeft;
                sizeLab.textColor = kBlackColor;
                sizeLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:sizeLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"5"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"零售价: ￥%0.2lf",[model.retailPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"零售价: HK$%0.2lf",[model.retailPrice doubleValue]/100.f];
                }
                int height = font;
                if ([sizeValue.value containsString:@"+5"]) {
                    height = bigFont;
                }
                UILabel *retailPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                retailPriceLab.text = retailPrice;
                retailPriceLab.textAlignment = NSTextAlignmentLeft;
                retailPriceLab.textColor = kBlackColor;
                retailPriceLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:retailPriceLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"6"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"折扣价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"折扣价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                int height = font;
                if ([sizeValue.value containsString:@"+6"]) {
                    height = bigFont;
                }
                UILabel *retailPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                retailPriceLab.text = retailPrice;
                retailPriceLab.textAlignment = NSTextAlignmentLeft;
                retailPriceLab.textColor = kBlackColor;
                retailPriceLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:retailPriceLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"7"] && model.component.length > 0) {
                NSString *component = [NSString stringWithFormat:@"成分含量: %@",model.component];
                int height = font;
                if ([sizeValue.value containsString:@"+7"]) {
                    height = bigFont;
                }
                if (model.component2.length > 0) {
                    height = height * 2;
                }
                UILabel *componentLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width - x - 20, height + labSpace)];
                componentLab.text = component;
                componentLab.textAlignment = NSTextAlignmentLeft;
                componentLab.textColor = kBlackColor;
                componentLab.font = [UIFont systemFontOfSize:height];
                if (model.component2.length > 0) {
                    componentLab.font = [UIFont systemFontOfSize:height/2];
                }
                componentLab.numberOfLines = 2;
                [bitView addSubview:componentLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"8"] && model.executionStandard.length > 0) {
                NSString *executionStandard = [NSString stringWithFormat:@"执行标准: %@",model.executionStandard];
                int height = font;
                if ([sizeValue.value containsString:@"+8"]) {
                    height = bigFont;
                }
                UILabel *executionStandardLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                executionStandardLab.text = executionStandard;
                executionStandardLab.textAlignment = NSTextAlignmentLeft;
                executionStandardLab.textColor = kBlackColor;
                executionStandardLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:executionStandardLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"9"] && model.securityCategory.length > 0) {
                NSString *securityCategory = [NSString stringWithFormat:@"安全类别 : %@",model.securityCategory];
                int height = font;
                if ([sizeValue.value containsString:@"+9"]) {
                    height = bigFont;
                }
                UILabel *securityCategoryLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                securityCategoryLab.text = securityCategory;
                securityCategoryLab.textAlignment = NSTextAlignmentLeft;
                securityCategoryLab.textColor = kBlackColor;
                securityCategoryLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:securityCategoryLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"10"] && model.qualityGrade.length > 0) {
                NSString *qualityGrade = [NSString stringWithFormat:@"质量等级 : %@",model.qualityGrade];
                int height = font;
                if ([sizeValue.value containsString:@"+10"]) {
                    height = bigFont;
                }
                UILabel *qualityGradeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                qualityGradeLab.text = qualityGrade;
                qualityGradeLab.textAlignment = NSTextAlignmentLeft;
                qualityGradeLab.textColor = kBlackColor;
                qualityGradeLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:qualityGradeLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"11"] && model.washingMode.length > 0) {
                NSString *washingMode = [NSString stringWithFormat:@"洗涤方式 : %@",model.washingMode];
                int height = font;
                if ([sizeValue.value containsString:@"+11"]) {
                    height = bigFont;
                }
                UILabel *washingModeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                washingModeLab.text = washingMode;
                washingModeLab.textAlignment = NSTextAlignmentLeft;
                washingModeLab.textColor = kBlackColor;
                washingModeLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:washingModeLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"13"] && model.brandName.length > 0) {
                NSString *washingMode = [NSString stringWithFormat:@"品牌 : %@",model.brandName];
                int height = font;
                if ([sizeValue.value containsString:@"+13"]) {
                    height = bigFont;
                }
                UILabel *washingModeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                washingModeLab.text = washingMode;
                washingModeLab.textAlignment = NSTextAlignmentLeft;
                washingModeLab.textColor = kBlackColor;
                washingModeLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:washingModeLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"14"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"特价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"特价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                int height = font;
                if ([sizeValue.value containsString:@"+14"]) {
                    height = bigFont;
                }
                UILabel *retailPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                retailPriceLab.text = retailPrice;
                retailPriceLab.textAlignment = NSTextAlignmentLeft;
                retailPriceLab.textColor = kBlackColor;
                retailPriceLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:retailPriceLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"15"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"会员价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"会员价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                int height = font;
                if ([sizeValue.value containsString:@"+15"]) {
                    height = bigFont;
                }
                UILabel *retailPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                retailPriceLab.text = retailPrice;
                retailPriceLab.textAlignment = NSTextAlignmentLeft;
                retailPriceLab.textColor = kBlackColor;
                retailPriceLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:retailPriceLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"16"] && model.ground.length > 0) {
                NSString *ground = [NSString stringWithFormat:@"场地 : %@",model.ground];
                int height = font;
                if ([sizeValue.value containsString:@"+16"]) {
                    height = bigFont;
                }
                if (model.ground2.length > 0) {
                    height = height * 2;
                }
                UILabel *groundLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width - x - 20, height + labSpace)];
                groundLab.text = ground;
                groundLab.textAlignment = NSTextAlignmentLeft;
                groundLab.textColor = kBlackColor;
                groundLab.font = [UIFont systemFontOfSize:height];
                if (model.ground2.length > 0) {
                    groundLab.font = [UIFont systemFontOfSize:height/2];
                }
                groundLab.numberOfLines = 2;
                [bitView addSubview:groundLab];
                y += height + labSpace;
            }
            if ([arrStr isEqualToString:@"17"] && model.dealer.length > 0) {
                NSString *dealer = [NSString stringWithFormat:@"经销商 : %@",model.dealer];
                int height = font;
                if ([sizeValue.value containsString:@"+17"]) {
                    height = bigFont;
                }
                UILabel *dealerLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width, height + labSpace)];
                dealerLab.text = dealer;
                dealerLab.textAlignment = NSTextAlignmentLeft;
                dealerLab.textColor = kBlackColor;
                dealerLab.font = [UIFont systemFontOfSize:height];
                [bitView addSubview:dealerLab];
                y += height;
            }
            
            if ([arrStr isEqualToString:@"12"]) {
                isBarcode = true;
                    NSString *barcode = model.barcode;
                    if (model.barcodeSingle.length > 0) {
                        barcode = model.barcodeSingle;
                    }
                    BOOL isPrint = [self validateNumber:barcode];
                    if (barcode.length > 0) {
                        if (isPrint == YES) {
                            if ([labelLayout.value isEqualToString:@"3"]) {
                                UIImageView *bitImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, y, 228, 50)];
                                bitImageV.image = [self resizeCodeWithString:barcode BCSize:CGSizeMake(228, 50)];
                                [bitView addSubview:bitImageV];
                                y += 52;
                            } else {
                                UIImageView *bitImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, y, 300, 60)];
                                bitImageV.image = [self resizeCodeWithString:barcode BCSize:CGSizeMake(300, 60)];
                                y += 60;
                                [bitView addSubview:bitImageV];
                            }
                            
                            UILabel *barcodeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, y, bitView.width - x - 20, font + labSpace)];
                            barcodeLab.text = barcode;
                            barcodeLab.textAlignment = NSTextAlignmentCenter;
                            barcodeLab.textColor = kBlackColor;
                            barcodeLab.font = [UIFont systemFontOfSize:font];
                            [bitView addSubview:barcodeLab];
                            y += font + labSpace;
                        }
                    }
                }
        }
        bitView.height = y;
        [command addBitmapwithX:x + MHT_x withY:top withMode:0 withWidth:bitView.width - x - MHT_x withImage:[self imageFromView:bitView]];
        [command addPrint:1 :printNum];
    } else {
        if ([labelLayout.value isEqualToString:@"3"]) {
            j = 30;
            width = 240;
        }else if ([labelLayout.value isEqualToString:@"1"] || [labelLayout.value isEqualToString:@"2"]) {
            j = 40;
            int count = 0;
            
            for (int i = 0; i < arr.count; i++) {
                NSString *arrStr = arr[i];
                if (i == 0) {
                    if ([arrStr isEqualToString:@"0"]) {
                        count++;
                    }
                }else if ([arrStr isEqualToString:@"7"]) {
                    //                model.component
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.component length];i++){
                        int a = [model.component characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 108 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 108 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.component1 = [model.component substringToIndex:len - 3];
                            model.component2 = [model.component substringFromIndex:len - 3];
                        }else {
                            model.component1 = [model.component substringToIndex:len];
                            model.component2 = [model.component substringFromIndex:len];
                        }
                    }
                    count++;
                    
                }else if ([arrStr isEqualToString:@"2"]) {
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.productName length];i++){
                        int a = [model.productName characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 60 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 60 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.productName1 = [model.productName substringToIndex:len - 3];
                            model.productName2 = [model.productName substringFromIndex:len - 3];
                        }else {
                            model.productName1 = [model.productName substringToIndex:len];
                            model.productName2 = [model.productName substringFromIndex:len];
                        }
                    }
                    count++;
                }else if ([arrStr isEqualToString:@"16"]) {
                    //                model.ground
                    int Chinese = 0;
                    int English = 0;
                    int len = 0;
                    for(int i = 0; i< [model.ground length];i++){
                        int a = [model.ground characterAtIndex:i];
                        if( a > 0x4e00 && a < 0x9fff){
                            Chinese ++;
                        }else {
                            English ++;
                        }
                        if (Chinese *24 + English *12 + 60 < 301) {
                            len++;
                        }
                    }
                    
                    if (Chinese * 24 + English *12 + 60 > 300) {
                        count++;
                        if ([printName isEqualToString:@"MHT-L58G"]) {
                            model.ground1 = [model.ground substringToIndex:len - 3];
                            model.ground2 = [model.ground substringFromIndex:len - 3];
                        }else {
                            model.ground1 = [model.ground substringToIndex:len];
                            model.ground2 = [model.ground substringFromIndex:len];
                        }
                    }
                    count++;
                }else {
                    if ([arrStr integerValue] > 0) {
                        count++;
                    }
                }
            }
            if (count < 10) {
                j = 45;
            }else if (count > 10) {
                j = 32;
            }
            if ([labelLayout.value isEqualToString:@"2"]) {
                j = 40;
            }
        }else if ([labelLayout.value isEqualToString:@"4"]) {
            j = 40;
        }
        
        if ([printName isEqualToString:@"MHT-L58G"]  || [printName isEqualToString:@"XP-T202UA"]) {
            [command addDensity:20];
            if ([labelLayout.value isEqualToString:@"3"]) {
                j = 26;
            }
        }
        for (int i = 0; i < arr.count; i++) {
            NSString *arrStr = arr[i];
            if ([arrStr isEqualToString:@"0"]) {
                int Chinese = 0;
                int English = 0;
                for(int i = 0; i< [storeName length];i++){
                    int a = [storeName characterAtIndex:i];
                    if( a > 0x4e00 && a < 0x9fff){
                        Chinese ++;
                    }else {
                        English ++;
                    }
                }
                int length = Chinese * 24 + English * 12;
                int x2 = 0;
                if (length < width) {
                    x2 = (width - length) / 2;
                    if (x2 > 20) {
                        x2 -= 12;
                    }
                }
                [command addTextwithX:x2  withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:storeName];
                y += j;
            }
            
            if ([arrStr isEqualToString:@"1"]) {
                NSString *productCode = [NSString stringWithFormat:@"款号: %@",model.productCode];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:productCode];
                y += j;
            }
            if ([arrStr isEqualToString:@"2"]) {
                if (model.productName1.length > 0) {
                    NSString *productName1 = [NSString stringWithFormat:@"名称: %@",model.productName1];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:productName1];
                    y += j;
                    
                    NSString *productName2 = [NSString stringWithFormat:@"%@",model.productName2];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:productName2];
                    y += j;
                }else {
                    NSString *productName = [NSString stringWithFormat:@"名称: %@",model.productName];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:productName];
                    y += j;
                }
            }
            if ([arrStr isEqualToString:@"3"] && model.color.length > 0) {
                NSString *color = [NSString stringWithFormat:@"颜色: %@",model.color];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:color];
                y += j;
            }
            if ([arrStr isEqualToString:@"4"] && model.size.length > 0) {
                NSString *size = [NSString stringWithFormat:@"尺码: %@",model.size];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:size];
                y += j;
            }
            if ([arrStr isEqualToString:@"5"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"零售价: ￥%0.2lf",[model.retailPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"零售价: HK$%0.2lf",[model.retailPrice doubleValue]/100.f];
                }
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:retailPrice];
                y += j;
            }
            if ([arrStr isEqualToString:@"6"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"折扣价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"折扣价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:retailPrice];
                y += j;
            }
            if ([arrStr isEqualToString:@"7"] && model.component.length > 0) {
                if (model.component1.length > 0) {
                    NSString *component1 = [NSString stringWithFormat:@"成分含量: %@",model.component1];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:component1];
                    y += j;
                    
                    NSString *component2 = [NSString stringWithFormat:@"%@",model.component2];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:component2];
                    y += j;
                }else {
                    NSString *component = [NSString stringWithFormat:@"成分含量: %@",model.component];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:component];
                    y += j;
                }
            }
            if ([arrStr isEqualToString:@"8"] && model.executionStandard.length > 0) {
                NSString *executionStandard = [NSString stringWithFormat:@"执行标准: %@",model.executionStandard];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:executionStandard];
                y += j;
            }
            if ([arrStr isEqualToString:@"9"] && model.securityCategory.length > 0) {
                NSString *securityCategory = [NSString stringWithFormat:@"安全类别 : %@",model.securityCategory];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:securityCategory];
                y += j;
            }
            if ([arrStr isEqualToString:@"10"] && model.qualityGrade.length > 0) {
                NSString *qualityGrade = [NSString stringWithFormat:@"质量等级 : %@",model.qualityGrade];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:qualityGrade];
                y += j;
            }
            if ([arrStr isEqualToString:@"11"] && model.washingMode.length > 0) {
                NSString *washingMode = [NSString stringWithFormat:@"洗涤方式 : %@",model.washingMode];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode];
                y += j;
            }
            if ([arrStr isEqualToString:@"13"] && model.brandName.length > 0) {
                NSString *washingMode = [NSString stringWithFormat:@"品牌 : %@",model.brandName];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode];
                y += j;
            }
            if ([arrStr isEqualToString:@"14"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"特价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"特价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:retailPrice];
                y += j;
            }
            if ([arrStr isEqualToString:@"15"]) {
                NSString *retailPrice = [NSString stringWithFormat:@"会员价: ￥%0.2lf",[model.discountPrice doubleValue]/100.f];
                if (isHongKong == YES) {
                    retailPrice = [NSString stringWithFormat:@"会员价: HK$%0.2lf",[model.discountPrice doubleValue]/100.f];
                }
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:retailPrice];
                y += j;
            }
            if ([arrStr isEqualToString:@"16"] && model.ground.length > 0) {
                if (model.ground1.length > 0) {
                    NSString *washingMode = [NSString stringWithFormat:@"场地 : %@",model.ground1];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode];
                    y += j;
                    
                    NSString *washingMode2 = [NSString stringWithFormat:@"%@",model.ground2];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode2];
                    y += j;
                }else {
                    NSString *washingMode = [NSString stringWithFormat:@"场地 : %@",model.ground];
                    [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode];
                    y += j;
                }
            }
            if ([arrStr isEqualToString:@"17"] && model.dealer.length > 0) {
                NSString *washingMode = [NSString stringWithFormat:@"经销商 : %@",model.dealer];
                [command addTextwithX:x withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:washingMode];
                y += j;
            }
            
            if ([arrStr isEqualToString:@"12"]) {
                int imageX = x;
                NSString *barcode = model.barcode;
                if (model.barcodeSingle.length > 0) {
                    barcode = model.barcodeSingle;
                }
                BOOL isPrint = [self validateNumber:barcode];
                if (barcode.length > 0) {
                    if (isPrint == YES) {
                        UIImage *barcodeImage = nil;
                        if ([labelLayout.value isEqualToString:@"3"]) {
                            barcodeImage = [self resizeCodeWithString:barcode BCSize:CGSizeMake(208, 36)];
                            [command addBitmapwithX:imageX withY:y-4 withMode:0 withWidth:208 withImage:barcodeImage];
                            y += 36;
                            
                            int Chinese = 0;
                            int English = 0;
                            for(int i = 0; i< [barcode length];i++){
                                int a = [barcode characterAtIndex:i];
                                if( a > 0x4e00 && a < 0x9fff){
                                    Chinese ++;
                                }else {
                                    English ++;
                                }
                            }
                            int length = Chinese * 24 + English * 12;
                            int x2 = 0;
                            if (length < width) {
                                x2 = (width - length) / 2;
                                if (x2 > 20) {
                                    x2 -= 12;
                                }
                            }
                            if ([printName isEqualToString:@"MHT-L58G"] || [printName isEqualToString:@"XP-T202UA"]) {
                                [command addTextwithX:x2 withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:barcode];
                            }else {
                                [command addTextwithX:x2 withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:barcode];
                            }
                            
                            //                        [command add1DBarcode:0 :y :@"CODE128" :30 :1 :0 :2 :2 :barcode];
                        }else {
                            if ([labelLayout.value isEqualToString:@"4"]) {
                                [command add1DBarcode:64 :y :@"CODE128" :80 :1 :0 :2 :2 :barcode];
                            }else {
                                barcodeImage = [self resizeCodeWithString:barcode BCSize:CGSizeMake(280, 45)];
                                [command addBitmapwithX:imageX withY:y withMode:0 withWidth:280 withImage:barcodeImage];
                                y += 48;
                                
                                int Chinese = 0;
                                int English = 0;
                                for(int i = 0; i< [barcode length];i++){
                                    int a = [barcode characterAtIndex:i];
                                    if( a > 0x4e00 && a < 0x9fff){
                                        Chinese ++;
                                    }else {
                                        English ++;
                                    }
                                }
                                int length = Chinese * 24 + English * 12;
                                int x2 = 0;
                                if (length < width) {
                                    x2 = (width - length) / 2;
                                    if (x2 > 20) {
                                        x2 -= 12;
                                    }
                                }
                                [command addTextwithX:x2 withY:y withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:barcode];
                            }
                            
                        }
                    }
                }
            }
        }
        
        if (y > 21) {
            [command addPrint:1 :printNum];
        }
    }
    
    return [command getCommand];
}


-(SASalesInvoiceDetailAPI *)salesInvoiceDetailAPI {
    if (!_salesInvoiceDetailAPI) {
        _salesInvoiceDetailAPI = [SASalesInvoiceDetailAPI apiWithDelegate:self];
    }
    return _salesInvoiceDetailAPI;
}

-(SAWarehousePurchaseInvoiceDetailAPI *)warehousePurchaseInvoiceDetailAPI {
    if (!_warehousePurchaseInvoiceDetailAPI) {
        _warehousePurchaseInvoiceDetailAPI = [SAWarehousePurchaseInvoiceDetailAPI apiWithDelegate:self];
    }
    return _warehousePurchaseInvoiceDetailAPI;
}

-(SASalesReturnDetailAPI *)salesReturnDetailAPI {
    if (!_salesReturnDetailAPI) {
        _salesReturnDetailAPI = [SASalesReturnDetailAPI apiWithDelegate:self];
    }
    return _salesReturnDetailAPI;
}

- (UIImage*)scaleToSize:(UIImage*)img size:(CGSize)size{
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

// 生成条形码
- (UIImage *)resizeCodeWithString:(NSString *)text BCSize:(CGSize)size
{
    CIImage *image = [self generateBarCodeImage:text];
    
    return [self resizeCodeImage:image withSize:size];
}

- (CIImage *)generateBarCodeImage:(NSString *)source
{
    // iOS 8.0以上的系统才支持条形码的生成，iOS8.0以下使用第三方控件生成
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 注意生成条形码的编码方式
        NSData *data = [source dataUsingEncoding: NSASCIIStringEncoding];
        CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
        [filter setValue:data forKey:@"inputMessage"];
        // 设置生成的条形码的上，下，左，右的margins的值
        [filter setValue:[NSNumber numberWithInteger:0] forKey:@"inputQuietSpace"];
        return filter.outputImage;
    }else{
        return nil;
    }
}

- (UIImage *)resizeCodeImage:(CIImage *)image withSize:(CGSize)size
{
    if (image) {
        CGRect extent = CGRectIntegral(image.extent);
        CGFloat scaleWidth = size.width/CGRectGetWidth(extent);
        CGFloat scaleHeight = size.height/CGRectGetHeight(extent);
        size_t width = CGRectGetWidth(extent) * scaleWidth;
        size_t height = CGRectGetHeight(extent) * scaleHeight;
        CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
        CGContextRef contentRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, (CGBitmapInfo)kCGImageAlphaNone);
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef imageRef = [context createCGImage:image fromRect:extent];
        CGContextSetInterpolationQuality(contentRef, kCGInterpolationNone);
        CGContextScaleCTM(contentRef, scaleWidth, scaleHeight);
        CGContextDrawImage(contentRef, extent, imageRef);
        CGImageRef imageRefResized = CGBitmapContextCreateImage(contentRef);
        UIImage *barImage = [UIImage imageWithCGImage:imageRefResized];
        
        //Core Foundation 框架下内存泄露问题。
        CGContextRelease(contentRef);
        CGColorSpaceRelease(colorSpaceRef);
        CGImageRelease(imageRef);
        CGImageRelease(imageRefResized);
        return barImage;
    }else{
        return nil;
    }
}

- (UIImage*)createCodeWithString:(NSString*)str
                            size:(CGSize)size
                      CodeFomart:(ZXBarcodeFormat)format
{
    ZXMultiFormatWriter *writer = [[ZXMultiFormatWriter alloc] init];
    ZXBitMatrix *result = [writer encode:str format:format width:size.width height:size.height error:nil];
    ZXImage *image = [ZXImage imageWithMatrix:result];
    //    UIImage *image2 = [UIImage imageWithCGImage:image.cgimage];
    //    return [self resizeCodeImage:image2.CIImage withSize:size];
    return [UIImage imageWithCGImage:image.cgimage];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*/-"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

-(UIImage *)imageFromView:(UIView *)view {
    // 1. 创建一个新的图像上下文，大小与view的bounds相匹配
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    
    // 2. 获取当前图像上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 3. 将view的层级渲染到上下文中
    [view.layer renderInContext:context];
    
    // 4. 从上下文中获取生成的图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 5. 结束图像上下文
    UIGraphicsEndImageContext();
    
    // 6. 返回生成的图片
    return image;
}

@end
